package com.tamakloe.guestbook;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
//import javax.faces.component.UIInput;
import javax.faces.context.FacesContext;
import javax.faces.validator.ValidatorException;


/**
 * This bean is to be associated with a single message form in the JSF page. It provides under each
 * the Greeting DAO and several validation methods for the properties of the Greeting DTO.
 */
public abstract class AbstractGreetingForm extends AbstractForm {

    // Constants ----------------------------------------------------------------------------------

    /**
     * The message ID of the message-bundle to be associated with the 'Posted' message.
     * It contains one MessageFormat place holder for the User ID value.
     */
    public static final String POSTED_MESSAGE_ID = "guestbook.AbstractForm.POSTED";
    public static final String FAILED_MESSAGE_ID = "guestbook.DAOException";

    // Vars ---------------------------------------------------------------------------------------

    /**
     * The Greeting DAO associated with the User Form.
     */
    protected final GreetingJdoDao greetingJdoDao;

    // Init ---------------------------------------------------------------------------------------

    {
        // Obtain the UserDAO.
        //FacesContext facesContext = FacesContext.getCurrentInstance();
        greetingJdoDao = new GreetingJdoDao();
    }

    // Validators ---------------------------------------------------------------------------------

    /**
     * Validate the email address. It will fail if the email address is invalid or already exist.
     * @see javax.faces.validator.Validator#validate(FacesContext, UIComponent, Object)
     */
    public void validateEmail(FacesContext facesContext, UIComponent component, Object value)
        throws ValidatorException
    {
        String email = (String) value;
        if (!email.matches("^[\\w-~#&]+(\\.[\\w-~#&]+)*@([\\w-]+\\.)+[a-zA-Z]{2,5}$")) {
            throw new ValidatorException(
                new FacesMessage(getMessage(INVALID_MESSAGE_ID, getLabel(component))));
        }
    }

}

